package com.xuzz.xrpc.spring.context.annotation;

import com.xuzz.xrpc.spring.context.BootstrapApplicationListener;
import com.xuzz.xrpc.spring.context.processors.PropertiesBeanPostProcessor;
import com.xuzz.xrpc.spring.context.processors.PropertyConfigAware;
import com.xuzz.xrpc.spring.context.processors.ServiceAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
 * @description:
 * @author: xuzz
 * @create: 2020-02-21 17:44
 */
public class RPCConfigurationRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annotationAttributes
                = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableXRPC.class.getName()));

        //注册listener bean
        BeanDefinitionBuilder listenerBuilder = rootBeanDefinition(BootstrapApplicationListener.class);
        listenerBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        BeanDefinitionReaderUtils.registerWithGeneratedName(listenerBuilder.getBeanDefinition(), registry);

        //注册配置文件
//        BeanDefinitionBuilder propertiesProcessorBuilder = rootBeanDefinition(PropertiesBeanPostProcessor.class);
//        propertiesProcessorBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
//        BeanDefinitionReaderUtils.registerWithGeneratedName(propertiesProcessorBuilder.getBeanDefinition(), registry);
        BeanDefinitionBuilder propertiesProcessorBuilder = rootBeanDefinition(PropertyConfigAware.class);
        propertiesProcessorBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        BeanDefinitionReaderUtils.registerWithGeneratedName(propertiesProcessorBuilder.getBeanDefinition(), registry);

        //后置处理器扫描Service注解
        String[] scanPackages = annotationAttributes.getStringArray("scanPackages");
        BeanDefinitionBuilder builder = rootBeanDefinition(ServiceAnnotationBeanPostProcessor.class);
//        builder.addPropertyValue("scanPackages",scanPackages);
        builder.addConstructorArgValue(scanPackages);
        builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        BeanDefinitionReaderUtils.registerWithGeneratedName(builder.getBeanDefinition(), registry);
    }
}
